package cn.scau.server.service.impl;

import cn.scau.server.pojo.Notice;
import cn.scau.server.mapper.NoticeMapper;
import cn.scau.server.service.NoticeService;
import cn.scau.server.vo.ResultVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 代码不跑我先跑
 * @since 2025-03-30
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {
    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    @Transactional
    public ResultVO<Notice> publishNotice(String title, String content, Integer status, Integer deptId) {
        try {
            // 验证参数
            if (deptId == null) {
                return ResultVO.fail("部门ID不能为空");
            }
            if (title == null || title.trim().isEmpty()) {
                return ResultVO.fail("公告标题不能为空");
            }
            if (content == null || content.trim().isEmpty()) {
                return ResultVO.fail("公告内容不能为空");
            }
            if (status == null || (status != 0 && status != 1)) {
                return ResultVO.fail("状态必须为0(未发布)或1(已发布)");
            }

            // 创建公告对象
            Notice notice = new Notice();
            notice.setTitle(title);
            notice.setContent(content);
            notice.setStatus(status);
            notice.setDeptId(deptId);

            // 处理发布时间
            if (status == 1) {
                notice.setPublishTime(LocalDateTime.now());
            } else {
                notice.setPublishTime(null);
            }

            // 保存公告
            boolean success = save(notice);
            if (success) {
                return ResultVO.success("公告发布成功", notice);
            } else {
                return ResultVO.fail("公告发布失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("发布公告异常: " + e.getMessage());
        }
    }

    @Override
    public ResultVO<Page<Notice>> getPublishedNotices(Integer id, String title, String startDate, String endDate, Integer deptId, Integer pageNum, Integer pageSize) {
        try {
            QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
            // 基础条件：只查询已发布的公告(status=1)
            queryWrapper.eq("status", 1);

            // 处理日期范围
            LocalDate start = startDate == null || startDate.isEmpty()
                    ? LocalDate.of(1900, 1, 1)
                    : LocalDate.parse(startDate);

            LocalDate end = endDate == null || endDate.isEmpty()
                    ? LocalDate.now()
                    : LocalDate.parse(endDate);

            // 添加日期范围条件
            queryWrapper.between("publish_time",
                    start.atStartOfDay(),
                    end.atTime(23, 59, 59));

            // 添加可选条件
            if (id != null) {
                queryWrapper.eq("id", id);
            }

            if(title!=null){
                queryWrapper.like("title", title.trim());
            }

            if (deptId != null) {
                queryWrapper.eq("dept_id", deptId);
            }

            // 按发布时间降序排列
            queryWrapper.orderByDesc("publish_time");

            // 分页查询
            Page<Notice> page = new Page<>(pageNum, pageSize);
            noticeMapper.selectPage(page, queryWrapper);
            return ResultVO.success("查询成功", page);
        } catch (DateTimeParseException e) {
            return ResultVO.fail("日期格式不正确，请使用yyyy-MM-dd格式");
        } catch (Exception e) {
            return ResultVO.fail("查询公告异常: " + e.getMessage());
        }
    }
    @Override
    public ResultVO<Page<Notice>> getDraftNotices(Integer id, String title, Integer status, Integer deptId, Integer pageNum, Integer pageSize) {
        try {
            QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();

            // 基础条件：查询草稿(0)或已撤销(2)的公告
            if (status == null) {
                queryWrapper.in("status", 0, 2);
            } else {
                if (status != 0 && status != 2) {
                    return ResultVO.fail("状态参数错误，只能为0(未发布)或2(已撤销)");
                }
                queryWrapper.eq("status", status);
            }

            // 添加可选条件
            if (id != null) {
                queryWrapper.eq("id", id);
            }

            if(title!=null){
                queryWrapper.like("title", title.trim());
            }

            if (deptId != null) {
                queryWrapper.eq("dept_id", deptId);
            }

            // 分页查询
            Page<Notice> page = new Page<>(pageNum, pageSize);
            noticeMapper.selectPage(page, queryWrapper);
            return ResultVO.success("查询成功", page);
        } catch (Exception e) {
            log.error("查询草稿箱异常",e);
            return ResultVO.fail("查询草稿箱异常: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResultVO<Notice> editNotice(Integer id, Integer deptId, String title, String content) {
        try {
            // 参数验证
            if (id == null) {
                return ResultVO.fail("公告编号不能为空");
            }
            if (deptId == null) {
                return ResultVO.fail("部门编号不能为空");
            }
            if (title == null || title.trim().isEmpty()) {
                return ResultVO.fail("公告内容不能为空");
            }
            if (content == null || content.trim().isEmpty()) {
                return ResultVO.fail("公告内容不能为空");
            }

            // 查询要编辑的公告
            Notice notice = getById(id);
            if (notice == null) {
                return ResultVO.fail("找不到指定编号的公告");
            }

            // 检查公告状态
            if (notice.getStatus() != 0 && notice.getStatus() != 2) {
                return ResultVO.fail("只能编辑未发布(0)或已撤销(2)的公告");
            }

            // 更新公告信息
            notice.setDeptId(deptId);
            notice.setContent(content);
            notice.setTitle(title);

            boolean success = updateById(notice);
            if (success) {
                return ResultVO.success("公告编辑成功", notice);
            } else {
                return ResultVO.fail("公告编辑失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("编辑公告异常: " + e.getMessage());
        }
    }
    @Override
    @Transactional
    public ResultVO<Notice> changeNoticeStatus(Integer id, Integer status) {
        try {
            // 参数验证
            if (id == null) {
                return ResultVO.fail("公告编号不能为空");
            }
            if (status == null || (status != 1 && status != 2)) {
                return ResultVO.fail("状态参数错误，只能为1(发布)或2(撤销)");
            }

            // 查询公告
            Notice notice = getById(id);
            if (notice == null) {
                return ResultVO.fail("找不到指定编号的公告");
            }

            // 状态转换验证
            if (status == 1 && notice.getStatus() != 0 && notice.getStatus() != 2) {
                return ResultVO.fail("只能发布状态为未发布(0)或已撤销(2)的公告");
            }
            if (status == 2 && notice.getStatus() != 1) {
                return ResultVO.fail("只能撤销状态为已发布(1)的公告");
            }

            // 更新状态
            notice.setStatus(status);
            if (status == 1) {
                notice.setPublishTime(LocalDateTime.now());
            }

            boolean success = updateById(notice);
            if (success) {
                String message = status == 1 ? "公告发布成功" : "公告撤销成功";
                return ResultVO.success(message, notice);
            } else {
                return ResultVO.fail("状态变更失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("改变公告状态异常: " + e.getMessage());
        }
    }
    @Override
    @Transactional
    public ResultVO deleteNotice(Integer id) {
        try {
            // 参数验证
            if (id == null) {
                return ResultVO.fail("公告编号不能为空");
            }

            // 查询公告
            Notice notice = getById(id);
            if (notice == null) {
                return ResultVO.fail("找不到指定编号的公告");
            }

            // 状态验证
            if (notice.getStatus() != 0 && notice.getStatus() != 2) {
                return ResultVO.fail("只能删除未发布(0)或已撤销(2)的公告");
            }

            // 删除公告
            boolean success = removeById(id);
            if (success) {
                return ResultVO.success("公告删除成功");
            } else {
                return ResultVO.fail("公告删除失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("删除公告异常: " + e.getMessage());
        }
    }
    @Override
    public ResultVO<Notice> viewNoticeContent(Integer id) {
        try {
            // 参数验证
            if (id == null) {
                return ResultVO.fail("公告编号不能为空");
            }

            // 查询公告
            Notice notice = getById(id);
            if (notice == null) {
                return ResultVO.fail("找不到指定编号的公告");
            }

            // 返回公告内容
            return ResultVO.success("查询成功", notice);
        } catch (Exception e) {
            return ResultVO.fail("查看公告内容异常: " + e.getMessage());
        }
    }
}
